package com.jxt.myapp.controller;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.jxt.myapp.domain.User;
import com.jxt.myapp.domain.jqgrid.JqGridParameter;
import com.jxt.myapp.domain.json.CustomGenericResponse;
import com.jxt.myapp.domain.json.CustomUserResponse;
import com.jxt.myapp.service.IPermissionsService;
import com.jxt.myapp.utils.DateUtils;
import com.jxt.myapp.utils.PaginationUtils;

@Controller
@RequestMapping("/user")
public class UserController {

	@Resource(name = "permissionsService")
	private IPermissionsService permissionsService;

	private static final Logger logger = LoggerFactory
	.getLogger(UserController.class);


	@RequestMapping(method = RequestMethod.GET)
	public @ResponseBody
	CustomUserResponse getAllUser(@RequestParam("page") String page,
			@RequestParam("rows") String rows,
			@RequestParam("sidx") String sidx,
			@RequestParam("sord") String sord,
			@RequestParam("_search") Boolean isSearch,
			@RequestParam(value = "filters", required = false) String filters) {

		logger.info("GetAllUser Menthod!");

		JqGridParameter jqGridParameter = new JqGridParameter();

		jqGridParameter.setPage(Integer.parseInt(page));
		jqGridParameter.setRows(Integer.parseInt(rows));
		jqGridParameter.setSidx(sidx);
		jqGridParameter.setSord(sord);
		jqGridParameter.setFilters(filters);

		long records = 0;

		List<User> users = Collections.emptyList();

		if (StringUtils.isNotEmpty(filters)) {
			// 有查询字段
			users = permissionsService.getAllUserByParameter(jqGridParameter);
			records = permissionsService
					.getAllUserByParameterCount(jqGridParameter);
		} else {
			// 无查询字段

			users = permissionsService.getAllUser(jqGridParameter);
			records = permissionsService.getAllUserCount(jqGridParameter);
		}

		long total = PaginationUtils
				.getPageCount(records, Long.parseLong(rows));

		CustomUserResponse response = new CustomUserResponse();

		response.setRows(users);

		response.setRecords(String.valueOf(records));

		response.setPage(page);

		response.setTotal(String.valueOf(total));

		return response;
	}

	@RequestMapping(value = "/edit", method = RequestMethod.POST)
	public @ResponseBody
	CustomGenericResponse editUser(
			@RequestParam("id") String id,
			@RequestParam(value = "loginName", required = false) String loginName,
			@RequestParam(value = "password", required = false) String password,
			@RequestParam(value = "name", required = false) String name,
			@RequestParam(value = "email", required = false) String email,
			@RequestParam(value = "tel", required = false) String tel,
			@RequestParam(value = "group_id", required = false) String groupId,
			@RequestParam(value = "state", required = false) int state) {

		logger.info("Edit User Method!");

		User user = new User();
		user.setId(id);
		user.setLoginName(loginName);
		user.setPassword(password);
		user.setName(name);
		user.setEmail(email);
		user.setGroupId(groupId);
		user.setTel(tel);
		user.setWithdrawTime(DateUtils.nowTime());

		int success = permissionsService.updateUser(user);
		CustomGenericResponse response = new CustomGenericResponse();
		if (success == 1) {
			response.setSuccess(true);
			response.setMessage("更新成功!");
		} else {
			response.setSuccess(false);
			response.setMessage(" 修改失败!");
		}

		return response;

	}

	@RequestMapping(value = "/add", method = RequestMethod.POST)
	public @ResponseBody
	CustomGenericResponse addUser(
			@RequestParam(value = "id", required = false) String id,
			@RequestParam(value = "loginName", required = false) String loginName,
			@RequestParam(value = "password", required = false) String password,
			@RequestParam(value = "name", required = false) String name,
			@RequestParam(value = "email", required = false) String email,
			@RequestParam(value = "tel", required = false) String tel,
			@RequestParam(value = "group_id", required = false) String groupId,
			@RequestParam(value = "state", required = false) int state) {

		logger.info("Add User Method!");

		User user = new User();
		user.setLoginName(loginName);
		user.setPassword(password);
		user.setName(name);
		user.setEmail(email);
		user.setGroupId(groupId);
		user.setTel(tel);
		user.setCreateTime(DateUtils.nowTime());

		int success = permissionsService.addUser(user);

		CustomGenericResponse response = new CustomGenericResponse();

		if (success == 1) {

			response.setSuccess(true);
			response.setMessage("添加成功!");
		} else {
			response.setSuccess(false);
			response.setMessage("添加失败!");
		}
		return response;
	}

	/**
	 * 批量删除
	 * 
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/delete", method = RequestMethod.POST)
	public @ResponseBody
	CustomGenericResponse deleteMoreUsers(@RequestParam("id") String[] id) {

		logger.info("Delete User Method!");
		final int DELETE_STATE = 0;

		List<User> userList = new ArrayList<User>();

		for (int i = 0; i < id.length; i++) {
			User user = new User();
			user.setId(id[i]);
			user.setState(DELETE_STATE);
			user.setWithdrawTime(DateUtils.nowTime());
			userList.add(user);
		}

		int[] success = permissionsService.deleteUser(userList);
		
		CustomGenericResponse response = new CustomGenericResponse();

		boolean isSuccess = true;

		// 如果返回为-1,则表示操作失败.
		for (int i = 0; i < success.length; i++) {
			if (success[i] == -1) {
				isSuccess = false;
			}
		}
		if (isSuccess) {
			response.setSuccess(true);
			response.setMessage("批量删除成功!");
		} else {
			response.setSuccess(false);
			response.setMessage("批量删除失败!");
		}
		return response;
	}

}
